/**
 * 
 */
package org.coldlife.sim.display;

import java.awt.Graphics;

import javax.swing.JPanel;

/**
 * @author MYE02035
 *
 */
public class DrawTestPanel extends JPanel implements Runnable 
{
	private static final long serialVersionUID = -2054733856277914442L;

	private static final int SLEEP_TIME = 20;
	private static final double BOX_RATE = 100;// px/s 
	
	private Thread paintThread;
	private double boxSize;

	private boolean isRunning = false;

	public DrawTestPanel() 
	{
		super(true); // Double-buffered.
		
		boxSize = 20;
		paintThread = new Thread(this,"DrawPanel.paintThread");
	}
	
	public void start()
	{
		paintThread.start();
		isRunning = true;
	}
	
	public void run() 
	{
		double inc = 1;
		long lastFrame = System.nanoTime();
		while(isRunning)
		{
			long now = System.nanoTime();
			inc =  ((now-lastFrame) * 1e-9) * BOX_RATE * Math.signum(inc);
			lastFrame = now;
			
			if(boxSize+inc > this.getWidth() || boxSize+inc > this.getHeight())
			{
				boxSize = Math.min(getWidth(), getHeight());
				inc = -inc;
			}
			else if( boxSize < 0){
				boxSize = 0;
				inc = -inc;
			}
			this.boxSize += inc;
			
			long t0 = System.currentTimeMillis();
			while(System.currentTimeMillis() - t0 < SLEEP_TIME)
			{
				Thread.yield();
			}
			
			this.repaint();
		}
	}
	
	public void stop()
	{
		isRunning = false;
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawOval(0, 0, (int)boxSize, (int)boxSize);
	}
}
